<template>
  <view>
    <u-swiper :list="swiper" :title="true" height="350"></u-swiper>
    <u-modal :show-cancel-button="true" v-model="show" @confirm="confirm" @cancel="show = false" :content="content"></u-modal>
    <view class="tap">
      <view class="swiper-tap">
        <u-tabs-swiper ref="uTabs" :list="list" :current="current" @change="tabsChange"
                       :is-scroll="false"></u-tabs-swiper>
        <view class="icon" @tap="show1 = true">
          <u-icon name="plus" size="30"></u-icon>
        </view>
      </view>

      <view class="course-list" v-show="isShow">
        <u-empty v-if="isEmpty1" text="您还未创建任何课程" mode="list"></u-empty>
        <view :class="'card bg-img-' + ((index % 3) + 1)" v-for="(course,index) in courseList1" :key="index">
          <view class="begin">
            <view class="course-name" @tap="courseDetail1(course.id,course.name)">{{ course.name }}</view>
            <view class="icon">
              <u-icon name="more-dot-fill" size="50" @tap="func1(course.id)"></u-icon>
            </view>
          </view>
          <view class="end" @tap="courseDetail1(course.id,course.name)">
            <view class="person">{{ course.joinCount }}人</view>
            <view class="icon">
              <u-icon name="arrow-right" size="30"></u-icon>
            </view>
          </view>
        </view>
        <u-loadmore :status="status1" v-if="!isEmpty1"/>
      </view>
      <view class="course-list" v-show="!isShow">
        <u-empty v-if="isEmpty2" text="您还未加入任何课程" mode="list"></u-empty>
        <view :class="'card bg-img-' + ((index % 3) + 1)" v-for="(course,index) in courseList2" :key="index">
          <view class="begin">
            <view class="course-name" @tap="courseDetail(course.id,course.name)">{{ course.name }}</view>
            <view class="icon">
              <u-icon name="more-dot-fill" size="50" @tap="func2(course.id)"></u-icon>
            </view>
          </view>
          <view class="end" @tap="courseDetail(course.id,course.name)">
            <view class="person">{{ course.joinCount }}人</view>
            <view class="info">
              <text class="name">{{ course.username }}</text>
              <u-avatar :src="course.avatar"></u-avatar>
            </view>
          </view>
        </view>
        <u-loadmore :status="status2" v-if="!isEmpty2"/>
      </view>

    </view>
    <u-action-sheet :list="list1" @click="click1" v-model="show1"></u-action-sheet>
    <u-action-sheet :list="list2" @click="click2" v-model="show2"></u-action-sheet>
    <u-action-sheet :list="list3" @click="click3" v-model="show3"></u-action-sheet>

  </view>
</template>


<script>
import {websocketObj} from '@/utils/websocket.js';
import {PrivateChatMsg, DataContent} from '@/utils/chatObject.js';
import {getSwiper} from "../../utils/constants";
import {networkStatus} from "../../utils/chat_utils";

export default {
  data() {
    return {
      list1: [{text: '创建课程'},{text: '加入课程'},{text: '我的归档'}],
      list2: [{text: '置顶'},{text: '退出班级'},{text: '参与签到'}],
      list3: [{text: '置顶'},{text: '课程信息'},{text: '签到'}],
      // 默认的轮播图，真实的从数据库获取
      swiper: getSwiper(),
      // 判断是否显示数据为空
      isEmpty1: false,
      isEmpty2: false,
      // 判断是否执行我加入的课程的初始化方法
      flag: false,
      // 当前tab
      current: 0,
      // 控制底部栏是否显示
      show1: false,
      show2: false,
      show3: false,
      // 控制显示我教的课程和我加入的课程
      isShow: true,
      list: [
        {
          name: '我教的课'
        },
        {
          name: '我听的课'
        }
      ],
      courseList2: [],
      courseList1: [],
      status1: '',
      status2: '',
      page1: 1,
      total1: 0,
      page2: 1,
      total2: 0,
      myTeachCourseCurrentId: '',
      myAttendCourseCurrentId: '',
      myTeachCourseCurrentIndex: '',
      myAttendCourseCurrentIndex: '',
      // 模态框
      show: false,
      content: '您确定要退出该课程吗？',
    }
  },
  onLoad() {
    networkStatus();
    // 获取轮播图
    this.$u.api.getSwiper().then(res => {
      this.swiper = res.data;
    })
    uni.$emit("setVuexUserInfo", {user: null, isLoginPage: false});
    this.initial();
    // 初始化
    websocketObj.sendMsg(new DataContent(1, new PrivateChatMsg(this.$store.getters.id, null, null, null, null), null));
    // 如果用户未登录，则在App.vue未执行该方法，需要用户登录之后（跳转到首页）再签收
    uni.$emit("unsignedHandler",this.$store.getters.id );
    uni.$on("indexInitial",this.initial);
    uni.$on("initial1",this.initial1);
  },
  onPullDownRefresh() {
    this.initial();
    setTimeout(() => {
      uni.stopPullDownRefresh();
    },1000)

  },
  onReachBottom() {
    if (this.isShow) {
      this.status1 = 'loading';
      if (this.page1 * 5 > this.total1) {
        setTimeout(() => {
          this.status1 = 'nomore';
        }, 1000)
      } else {
        this.page1 = ++this.page1;
        this.getMyTeachCourseList().then(res => {
          this.total1 = res.total;
          this.courseList1 = this.courseList1.concat(res.data);
        });
        this.status1 = 'loadmore';
      }
    } else {
      this.status2 = 'loading';
      if (this.page2 * 5 > this.total2) {
        setTimeout(() => {
          this.status2 = 'nomore';
        }, 1000)
      } else {
        this.page2 = ++this.page2;
        this.getMyAttendCourseList().then(res => {
          this.total2 = res.total;
          this.courseList2 = this.courseList2.concat(res.data);
        });
        this.status2 = 'loadmore';
      }
    }
  },
  methods: {
    initial(){
      this.page1 = 1;
      this.total1 = 0;
      this.getMyTeachCourseList().then(res => {
        if (res.total === 0){
          this.isEmpty1 = true;
          this.courseList1 = [];
          this.initial1();
        }else {
          this.isEmpty1 = false;
          this.total1 = res.total;
          this.courseList1 = res.data;
        }
      });

    },
    initial1(){
      this.page2 = 1;
      this.total2 = 0;
      this.getMyAttendCourseList().then(res => {
        if (res.total === 0){
          this.isEmpty2 = true;
          this.courseList1 = [];
        }else {
          this.isEmpty2 = false;
          this.total2 = res.total;
          this.courseList2 = res.data;
        }
        this.flag = true;
      });
    },
    click1(index) {
      if (index === 0){
        this.createCourse();
      }else if (index === 1){
        this.joinClass();
      }else {
        this.mineArchive();
      }
    },
    click2(index) {
      if (index === 0){
        this.first();
      }else if (index === 1){
        this.exitCourse();
      }else {
        this.sign(this.myAttendCourseCurrentId,false);
      }
    },
    click3(index) {
      if (index === 0){
        this.first();
      }else if (index === 1){
        this.courseInfo();
      }else {
        this.sign(this.myTeachCourseCurrentId,true);
      }
    },
    /**
     * 我教的课
     */
    async getMyTeachCourseList() {
      let userId = this.$store.state.user.id;
      if (userId === null || userId === '') {
        return;
      }
      let data = await this.$u.api.getMyTeachCourse(this.page1, userId);
      return data;
    },
    /**
     * 我听的课
     */
    async getMyAttendCourseList() {
      let userId = this.$store.state.user.id;
      if (userId === null || userId === '') {
        return;
      }
      let data = await this.$u.api.getMyAttendCourse(this.page2, userId);
      return data;
    },
    tabsChange(v) {
      this.current = v;
      // 如果初始化的时候未执行，则tab改变时执行
      if (v === 1 && !this.flag){
        this.initial1();
      }
      this.isShow = v !== 1;
    },
    createCourse() {
      this.$u.route('pages/create_course/create_course');
    },
    func1(id,index) {
      this.myTeachCourseCurrentIndex = index;
      this.myTeachCourseCurrentId = id;
      this.show3 = true;
    },
    func2(id,index) {
      this.myAttendCourseCurrentIndex = index;
      this.myAttendCourseCurrentId = id;
      this.show2 = true;
    },
    first() {
      console.log("置顶暂未实现")
    },
    exitCourse() {
      this.show = true;
      this.show2 = false;
    },
    confirm(){
      this.$u.api.kickOut(this.$store.getters.id, this.myAttendCourseCurrentId).then(res => {
        if (res.code === 200) {
          this.courseList2.splice(this.myAttendCourseCurrentIndex, 1);
          this.$u.toast("退出成功！")
        }
      })
    },
    joinClass() {
      this.$u.route('pages/join_course/join_course');
    },
    mineArchive() {
      this.$u.route('pages/mine_archive/mine_archive');
    },
    courseDetail1(id,name) {
      this.$u.route({
        url: 'pages/my_course_detail/my_course_detail',
        params: {
          id: id,
          name: name
        }
      })
    },
    courseDetail(id,name) {
      this.$u.route({
        url: 'pages/attend_course_detail/attend_course_detail',
        params: {
          id: id,
          name: name
        }
      })
    },
    courseInfo() {
      this.$u.route({
        url: 'pages/course_info/course_info',
        params: {
          id: this.myTeachCourseCurrentId
        }
      })
    },
    sign(id,isMyTeach) {
      let url = '';
      if(isMyTeach){
        url = 'pages/teacher_sign_list/teacher_sign_list';
      }else {
        url = 'pages/student_sign_list/student_sign_list';
      }
      this.$u.route({
        url: url,
        params: {
          id: id
        }
      })
    }
  }
}
</script>

<style lang="scss">
.swiper-tap {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .icon {
    width: 59rpx;
    height: 40rpx;
    color: white;
    margin-right: 10rpx;
    padding-left: 14rpx;
    padding-top: 2rpx;
    line-height: 40rpx;
    background-color: #C0C4CC;
  }
}

.bg-img-1 {
  background-image: linear-gradient(to bottom right, #4656ae, #99c8e4);
}


.bg-img-2 {
  background-image: linear-gradient(to bottom right, #3c9895, #6bdaa0);
}

.bg-img-3 {
  background-image: linear-gradient(to bottom right, #ff9900, #cbabab);
}


.course-list {
  margin: 20rpx 30rpx 0 10rpx;

  .card {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 220rpx;
    width: 100%;
    border-radius: 40rpx;
    color: white;
    font-size: 30rpx;
    font-weight: bold;
    margin: 20rpx 10rpx 20rpx;

    .begin {
      display: flex;
      justify-content: space-between;
      margin: 30rpx 30rpx 0;

      .course-name {
        font-size: 35rpx;
        font-weight: bolder;

      }

      .icon {
        z-index: 100;
        width: 50rpx;
        height: 50rpx;
      }
    }

    .end {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 30rpx 30rpx 30rpx;

      .info {
        display: flex;
        justify-content: space-evenly;
        align-items: center;

        .name {
          margin: 0 20rpx 0 0;
        }
      }
    }
  }
}

.group-nav {
  display: flex;
  flex-direction: column;
  justify-content: space-around;

  text {
    font-weight: bold;
    align-items: center;
    margin: 20rpx auto;
  }
}
</style>
